package com.firefly.netty.demo;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @description:
 * @author: lzg(萤火科技 ： 854378082 @ qq.com)
 * @date: 2022/9/16
 **/
@Slf4j
public class NettyClient {
    public DataFrame connect(String reqStr) throws Exception {
        String host = "127.0.0.1";
        Integer port = 9601;
        DataFrame responseResult = new DataFrame();
        NettyClientHandler nettyClientHandler = new NettyClientHandler();
        /**
         * 客户端的NIO线程组
         *
         */
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            /**
             * Bootstrap 是一个启动NIO服务的辅助启动类 客户端的
             */
            Bootstrap bootstrap = new Bootstrap();
            /**
             * 设置group
             */
            bootstrap = bootstrap.group(group);
            /**
             * 关联客户端通道
             */
            bootstrap = bootstrap.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
            /**
             * 设置 I/O处理类,主要用于网络I/O事件，记录日志，编码、解码消息
             */
            bootstrap = bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    //获取到pipeline
                    ChannelPipeline pipeline = ch.pipeline();
                    ch.pipeline().addLast("encoder", new StringEncoder());
                    // 属于ChannelInboundHandler，依照顺序执行（从上往下）
                    ch.pipeline().addLast("decoder", new StringDecoder());
                    /**
                     * 自定义ChannelInboundHandlerAdapter
                     */
                    ch.pipeline().addLast(nettyClientHandler);
                }
            });
            log.info("netty client start success!");
            /**
             * 连接服务端
             */
            ChannelFuture f = bootstrap.connect(host, port).sync();
            // 发送客户端的请求
            f.channel().writeAndFlush(Unpooled.copiedBuffer(reqStr.getBytes()));
            /**
             * 等待连接端口关闭
             */
            f.channel().closeFuture().sync();
            responseResult = nettyClientHandler.getResponseResult();
        } finally {
            /**
             * 退出，释放资源
             */
            group.shutdownGracefully();
        }
        return responseResult;
    }
}
